import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const foodsStore = createSlice({
    name: 'foods',
    initialState: {
        //商品列表
        foodsList: [],
        //菜单激活下标值
        activeIndex: 0,
        //购物车列表
        cartList: []
    },
    reducers: {
        //更改商品列表
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        //更改activeIndex
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        },
        //添加购物车
        addCart(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            if (item) {
                item.count++
            } else {
                state.cartList.push(action.payload)
            }
        },
        //count增
        increCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        //count减
        decreCount(state, action) {
            const item = state.cartList.find(item => item.id === action.payload.id)
            // if (item.count === 0) {
            //     state.cartList = state.cartList.filter(item => item.id !== action.payload.id);
            //     return
            // }
            // item.count--
            // console.log(item.count);

            if(item.count > 0){
                item.count--
                if(item.count === 0){
                    state.cartList = state.cartList.filter(item => item.id !== action.payload.id);
                }
            }
        },
        //清除购物车
        clearCart(state) {
            state.cartList = []
        }
    }
})

const { setFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart } = foodsStore.actions
const fetchFoodsList = () => {
    return async (diapatch) => {
        const res = await axios.get('http://localhost:3004/takeaway')
        diapatch(setFoodsList(res.data))
    }
}


const reducer = foodsStore.reducer

export default reducer
export { fetchFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart }


